package com.rao.gmall.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rao.gmall.common.result.Result;
import com.rao.gmall.common.result.ResultCodeEnum;
import com.rao.gmall.common.util.AuthContextHolder;
import com.rao.gmall.model.user.UserAddress;
import com.rao.gmall.model.user.UserInfo;
import com.rao.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author nzmxfan
 * @create 2021-08-16-20:13
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo info,
                        HttpServletRequest request){

        UserInfo userInfo = userService.login(info);

        if (userInfo == null){
            // 登陆失败
            return Result.build(null, ResultCodeEnum.PASSWDERROR);
        }
        // 登录成功
        Map<String, Object> success = userService.handleLoginSuccess(userInfo, request);

        return Result.ok(success);
    }

    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader(value = "token", required = false) String headerToken,
                         @CookieValue(value = "token", required = false) String cookieToken){

        String token = headerToken;
        if (StringUtils.isEmpty(token)){
            token = cookieToken;
        }

        userService.logout(token);

        return Result.ok();
    }

    @GetMapping("/getUserAddresses")
    public List<UserAddress> getUserAddresses(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.getUserAddresses(userId);
    }

}
